package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.project.entity.User;
import com.project.mapper.UserMapper;
import com.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lovo
 * @since 2023-07-21
 */
@Service
public class UserServiceImp extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public IPage<User> selectUserByName(Integer pageNO, String username) {
        return userMapper.selectUserByName(new Page<User>(pageNO,3),username);
    }

    @Override
    public String addUser(String username, String trueName, List<Integer> role) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("u_name",username);
        User user = userMapper.selectOne(wrapper);
        if (user != null){
            return "该用户已存在";
        }
        else{
            User newUser = new User();
            newUser.setName(username);
            newUser.setPwd("666");
            newUser.setTureName(trueName);
            userMapper.insert(newUser);
            userMapper.insertUserRoles(role,newUser.getUserId());
            return "ok";
        }

    }

    @Override
    public void deleteUser(Integer userId) {
        //先删除中间表
        userMapper.deleteUserRoles(userId);
        //删除用户表
        userMapper.deleteById(userId);

    }

    @Override
    public User selectUser(Integer userId) {
        return userMapper.selectUser(userId);
    }

    @Override
    public void updateUserRole(Integer userId, List<Integer> newRoleIds) {
        //先按用户ID删除旧的角色集合
        userMapper.deleteUserRoles(userId);
        //根据用户ID、新的角色ID数组批量添加用户角色中间表记录
        userMapper.insertUserRoles(newRoleIds,userId);
    }
}
